import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:hello_flutter/base/index.dart';

class ListViewWidget extends BasePage {
  const ListViewWidget({super.key});

  @override
  String getPageTitle() => 'ListView';

  @override
  Widget buildBody(BuildContext context) => Column(
        children: [
          const ListTile(
            title: Text('Words'),
          ),
          Expanded(
            child: _InfiniteListView(),
          ),
        ],
      );
}

class _InfiniteListView extends StatefulWidget {
  @override
  _InfiniteListViewState createState() => _InfiniteListViewState();
}

class _InfiniteListViewState extends State<_InfiniteListView> {
  static const loadingTag = '##loading##'; // 表尾标记

  final _words = <String>[loadingTag];

  void _retrieveData() {
    Future.delayed(const Duration(seconds: 2)).then((e) {
      setState(() {
        _words.insertAll(
          _words.length - 1,
          generateWordPairs().take(20).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _retrieveData();
  }

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      child: ListView.separated(
          itemBuilder: (context, index) {
            if (_words[index] == loadingTag) {
              if (_words.length - 1 < 100) {
                _retrieveData();
                return Container(
                  padding: const EdgeInsets.all(16),
                  alignment: Alignment.center,
                  child: const SizedBox.square(
                    dimension: 24,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.red,
                    ),
                  ),
                );
              } else {
                return Container(
                  padding: const EdgeInsets.all(16),
                  alignment: Alignment.center,
                  child: const Text(
                    '------ 没有更多了 ------',
                    style: TextStyle(color: Colors.grey),
                  ),
                );
              }
            }
            return ListTile(
              title: Text(_words[index]),
            );
          },
          separatorBuilder: (context, index) => const Divider(),
          itemCount: _words.length),
    );
  }
}
